<template>
  <view class="base-container">
    <view class="login">
      <view class="flex justify-between px-32rpx py-32rpx text-32rpx" :style="{ paddingTop: common.systemInfo.statusBarHeight + 10 + 'px' }">
        <uv-icon name="arrow-left" color="#303133" size="20px" @click="back"></uv-icon>
        <!-- <text class="text-#727687" @click="handleRegister">新用户注册</text> -->
      </view>
      <view class="login-top pt-44rpx">
        <view class="login-box-top flex">
          <text :class="{ 'title': true, 'active-title': activeTab === 1 }" @click="handleLoginWay(1)">手机登录</text>
          <text :class="{ 'title': true, 'active-title': activeTab === 2 }" @click="handleLoginWay(2)">账号登录</text>
        </view>
      </view>
      <view class="login-center">
        <view class="login-box">
          <view class="login-box-container mt-72rpx">
            <uv-form ref="loginFormRef" label-position="left" :rules="rules" :model="loginInfo">
              <uv-form-item v-if="activeTab === 1" prop="userInfo.phone">
                <uv-input v-model="loginInfo.userInfo.phone" placeholder="请输入手机号" maxlength="11" border="bottom"> </uv-input>
              </uv-form-item>
              <uv-form-item v-else-if="activeTab === 2" prop="userInfo.account">
                <uv-input v-model="loginInfo.userInfo.account" placeholder="请输入你的账号" border="bottom" maxlength="20"> </uv-input>
              </uv-form-item>
              <uv-form-item v-if="activeTab === 1" prop="userInfo.verifyCode">
                <view class="w-100%" style="position: relative">
                  <uv-input
                    v-model="loginInfo.userInfo.verifyCode"
                    placeholder="验证码"
                    :password="activeTab === 2 && isShowPassword ? true : false"
                    maxlength="6"
                    border="bottom"
                  >
                  </uv-input>
                  <view class="wrap" style="position: absolute; right: 0; top: 0">
                    <uv-toast ref="toast"></uv-toast>
                    <uv-code ref="codeRef" :keep-running="true" :seconds="seconds" @end="end" @start="start" @change="codeChange"></uv-code>
                    <view class="text-28rpx text-1C213E pr-40rpx mt-32rpx" @click="getCode">{{ tips }}</view>
                  </view>
                </view>
              </uv-form-item>
              <uv-form-item v-else-if="activeTab === 2" prop="userInfo.password">
                <view class="w-100%" style="position: relative">
                  <uv-input
                    v-model="loginInfo.userInfo.password"
                    placeholder="请输入账号密码"
                    :password="activeTab === 2 && isShowPassword ? true : false"
                    border="bottom"
                    maxlength="20"
                  >
                  </uv-input>
                  <view
                    class="text-28rpx text-1C213E pr-40rpx"
                    style="position: absolute; right: 0; top: 0"
                    @click="isShowPassword = !isShowPassword"
                  >
                    <image
                      :src="
                        !isShowPassword
                          ? 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-open.svg'
                          : 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-close.svg'
                      "
                      class="w-32rpx h-32rpx mt-15rpx mt-32rpx"
                    ></image>
                  </view>
                </view>
              </uv-form-item>
            </uv-form>
          </view>
        </view>

        <view class="login-btn pt-125rpx">
          <ReadAgreement ref="readAgreementRef" v-model="agreementProtocolFlag" @confirm="handleLogin" @cancel="handleCancel"></ReadAgreement>
          <mt-button :shake="false" class="mt-38rpx w-100%" style="border-radius: 192rpx" @click="handleLogin">登 录</mt-button>
        </view>
      </view>
    </view>
    <view class="login-footer safety-48">
      <uv-divider text="其他登录方式"></uv-divider>
      <view class="login-footer-logo safety-48">
        <uv-icon
          v-if="isWechatInstalled"
          name="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-wx.svg"
          size="46"
          @click="handleLogin(3)"
        ></uv-icon>
        <uv-icon
          v-if="commonStore.systemInfo.osName === 'ios'"
          name="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-iphone.svg"
          size="46"
          @click="handleLogin(4)"
        ></uv-icon>
      </view>
    </view>

    <app-renew></app-renew>
  </view>
</template>

<script setup>
import { sendVerifyCode, phone, login } from '@/api/login';
import { clientdictgetSimpleDictList } from '@/api/common';
import ReadAgreement from '@/pages/login/components/ReadAgreement.vue';
import { phoneCheck, passwordCheck } from '@/utils/regular';
import { clearOssKey } from '@/utils/tools';
import { handleWeixinLogin, handleAppleLogin } from '@/utils/login';
import userCommon from '@/store/common';
import useCommon from '@/store/common';

const common = useCommon();

const commonStore = userCommon();

const codeRef = ref(null);
const loginFormRef = ref(null);
const readAgreementRef = ref(null);

const activeTab = ref(1);
const tips = ref('获取验证码');
const agreementProtocolFlag = ref([]);
const seconds = ref(60);
const isShowPassword = ref(true);

const loginInfo = ref({
  userInfo: {
    phone: undefined,
    verifyCode: undefined,
    account: undefined,
    password: undefined
  }
});

const rules = ref({
  'userInfo.phone': [
    {
      type: 'string',
      required: true,
      message: '请输入手机号码',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        return phoneCheck(value);
      },
      message: '请输入正确的手机号',
      trigger: ['blur']
    }
  ],
  'userInfo.verifyCode': {
    type: 'string',
    required: true,
    message: '请输入验证码',
    trigger: ['blur', 'change']
  },
  'userInfo.account': {
    type: 'string',
    required: true,
    message: '请输入你的账号',
    trigger: ['blur', 'change']
  },
  'userInfo.password': [
    {
      type: 'string',
      required: true,
      message: '请输入账号密码',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        return passwordCheck(value);
      },
      message: '密码由 8 到 20 位的字母、数字或半角符号组成的字符串，并且确保该字符串不是 10 位以下的纯数字、纯字母或纯半角符号',
      trigger: ['blur']
    }
  ]
});

function back() {
  uni.navigateBack();
}
const codeChange = (text) => {
  tips.value = text;
};

const getCode = () => {
  loginFormRef.value.validateField('userInfo.phone', async (err) => {
    if (err && err.length) {
      return false;
    } else if (codeRef.value.canGetCode && loginInfo.value.userInfo.phone !== 'undefined') {
      uni.showLoading({
        title: '正在获取验证码'
      });
      uni.hideLoading();
      codeRef.value.start();
      const params = {
        phone: loginInfo.value.userInfo.phone,
        codeType: 1
      };
      const { code, data } = await sendVerifyCode(params);
      if (code === 200) {
        uni.showToast({
          title: '发送成功',
          icon: 'none'
        });
      }
    }
  });
};

const end = () => {
  // uni.$uv.toast('倒计时结束');
};

const start = () => {
  // uni.$uv.toast('倒计时开始');
};

const handleLoginWay = (type) => {
  // type 1 手机登录 2 账号登录
  activeTab.value = type;
  reset();
  agreementProtocolFlag.value = [];
};

const loginApp = (type) => {
  if (agreementProtocolFlag.value && agreementProtocolFlag.value.length) {
    switch (type) {
      case 1:
        // 手机号登录
        loginFormRef.value
          .validate()
          .then((result) => {
            if (result) {
              phone({
                ...loginInfo.value.userInfo,
                regionCode: ''
              }).then((res) => {
                uni.reLaunch({
                  url: '/pages/index/index'
                });
              });
            }
          })
          .catch((errors) => {});

        break;
      case 2:
        // 账户登录
        loginFormRef.value
          .validate()
          .then((result) => {
            if (result) {
              login(loginInfo.value.userInfo).then((res) => {
                uni.reLaunch({
                  url: '/pages/index/index'
                });
                uni.showToast({
                  title: '登录成功',
                  icon: 'none'
                });
              });
            }
          })
          .catch((errors) => {});

        break;
      case 3:
        // 微信登录
        handleWeixinLogin('');
        break;
      case 4:
        // 苹果登录
        handleAppleLogin('');
        break;
      default:
        break;
    }
  } else {
    readAgreementRef.value.openTips(type);
  }
};

// 账号密码登录
const handleLogin = (loginSign) => {
  // 登录之前清除ossKey
  clearOssKey();
  if (loginSign) {
    loginApp(loginSign);
  } else {
    loginApp(activeTab.value);
  }
};

const reset = () => {
  loginFormRef.value.resetFields();
  loginFormRef.value.clearValidate();
};

const isWechatInstalled = ref(false);
function handleShowIcon() {
  clientdictgetSimpleDictList({
    key: 'app_open_weixin'
  }).then((res) => {
    if (res.data[0]?.dictValue === '0') {
      isWechatInstalled.value = true;
    } else {
      isWechatInstalled.value = false;
    }
  });
}

onLoad(() => {
  handleShowIcon();
});
</script>

<style lang="scss" scoped>
.base-container {
  min-height: 100vh;
  background: #ffffff;
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: auto;
  .login {
    background: linear-gradient(234deg, rgba(20, 132, 238, 0.05) 0%, rgba(255, 255, 255, 0.05) 100%);
  }
  .login-top {
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: flex-start;
    padding-left: 48rpx;
    .login-box-top {
      .title {
        font-weight: 400;
        font-size: 48rpx;
        color: #adb0bd;
        margin-right: 64rpx;
      }
      .active-title {
        font-weight: 600;
        font-size: 48rpx;
        color: #1c213e;
      }
    }
    .login-icon {
      width: 342rpx;
      height: 134rpx;
    }
    .login-title {
      font-weight: 400;
      font-size: 24rpx;
      padding-top: 15rpx;
      color: #727687;
    }
  }
  .login-center {
    margin-top: 92rpx;
    padding: 0 32rpx 60rpx;
    .login-box {
      .login-btn {
        padding-bottom: 150rpx;
        :deep(.mt-button) {
          width: 100%;
          background: linear-gradient(130deg, #447fee 0%, #3d76e1 100%);
          border-radius: 190rpx 190rpx 190rpx 190rpx;
        }
      }
    }
  }
  .login-footer {
    padding: 30rpx 205rpx;
    width: 100%;
    box-sizing: border-box;
    // position: absolute;
    // bottom: 0;
    background-color: #fff;
    .login-footer-logo {
      margin-top: 18rpx;
      display: flex;
      justify-content: space-around;
      .logo-icon {
        width: 92rpx;
        height: 92rpx;
      }
    }
  }
}

:deep(.uv-form-item__body) {
  // padding-left: 40rpx !important;
}
:deep(.uv-form-item) {
  margin-top: 32rpx;
}
:deep(.uv-form-item__body__right__message) {
  margin-left: 26rpx !important;
}
:deep(.uv-input__content__field-wrapper__field) {
  padding: 17rpx 0;
}
</style>
